#encoding:utf8
import copy
import traceback
import json
from django.shortcuts import HttpResponse
from tools import get_request_info, get_request_field

return_data = dict(code=0, msg="", data="")
AUTH_CODE = "auth_code"


# 把exception wrap起来
def wrap_auth(auth=None):
    def wrapper_outer(func):
        def wrapper(request, *args, **kwargs):
            if auth:
                auth_code = get_request_field(request, "auth")
                if auth_code != auth:
                    raise Exception("auth code is not right")
            return func(*args, **kwargs)
        return wrapper
    return wrapper_outer


# 把exception wrap起来
def wrap_exception(func):
    def wrapper(*args, **kwargs):
        data = copy.deepcopy(return_data)
        try:
            return func(*args, **kwargs)
        except Exception, ex:
            data["code"] = -1
            data['msg'] = ex.message
            data['data'] = traceback.format_exc()
            return HttpResponse(json.dumps(data), content_type="application/json")
    return wrapper


# 函数只用关心内部的实现逻辑
def wrap_view_api(logger=None, auth=None):
    def wrap_outer(view_api_func):
        def wrap_inner(request, *args, **kwargs):
            if auth:
                auth_code = get_request_field(request, "auth")
                if auth_code != auth:
                    data = copy.copy(return_data)
                    data['code'] = -1
                    data['msg'] = "Authorization is falied"
                    return HttpResponse(json.dumps(data), content_type="application/json")

            req_info = get_request_info(request)
            client_ip = req_info['client_ip']
            data = copy.copy(return_data)

            result = view_api_func(request, *args, **kwargs)
            if logger:
                logger.info("request: client_ip: %s"%client_ip)
            data['data'] = result
            return HttpResponse(json.dumps(data), content_type="application/json")
        return wrap_inner
    return wrap_outer

